﻿
using GPS.MODELS;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GPS.DataAccessLayer;
using AutoMapper;
using PagedList;
using GPS.ENTITYS;
using GPS.COMMON;
using System.IO;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Oracle.ManagedDataAccess.Client;
using System.Data;
using Microsoft.AspNet.Identity;
using NPOI.HSSF.UserModel;
using OfficeOpenXml;
using System.Web.UI.WebControls;
using System.Web.UI;

namespace GPS.Controllers.GPS_BaoCao
{
    public class GPS_CB_GiapPhepXTLController : Controller
    {
        DbContextHelper<GPS_NVContext> _db = Singleton<DbContextHelper<GPS_NVContext>>.Inst;
        
        //
        // GET: /GPS_HTCapGPLX/
        #region Index
        public ActionResult Index(ViewReportModelGPS_CANHBAO_GPXTL SearchModel, int? currentPage)
        {
            string DVGTVT_MA = this.getCurrentUser().MA_TINHTP;
            ViewBag.checkuser = DVGTVT_MA;
            string getdvgtvt_Ma = GPS.DAL.Check_User.CheckUser(this.getCurrentUser().MA_TINHTP, SearchModel.pDVGTVT_MA);
            SearchModel.pDVGTVT_MA = getdvgtvt_Ma;
            TempData["DVGTVT_MA"] = getdvgtvt_Ma;

            var entities = Getdata(SearchModel);
            initialCategorySearchAction();

            var model = new List<RepostModelGPS_CANHBAO_GPXTL>();
            foreach (var currentEntity in entities)
            {
                model.Add(Mapper.Map<RepostModelGPS_CANHBAO_GPXTL>(currentEntity));
            }
            Int16 icount = 1;
            foreach (var item in model)
            {
                item.STT = icount;
                icount++;
            }
            if (SearchModel.ExportButton == "Xuất Excel")
            {
                try
                {
                    FileInfo template = new FileInfo(Server.MapPath(@"\Templates\GPS_Excel\CB_PhuongTinHetHanGiayPhep.xlsx"));
                    FileInfo newFile = new FileInfo(Server.MapPath(@"\Templates\GPS_Excel\CB_DonViHetHanGiayPhepNEW.xlsx"));

                    // Using the template to create the newFile...
                    using (OfficeOpenXml.ExcelPackage excelPackage = new OfficeOpenXml.ExcelPackage(newFile, template))
                    {
                        // Getting the complete workbook...
                        ExcelWorkbook myWorkbook = excelPackage.Workbook;
                        // Getting the worksheet by its name...
                        ExcelWorksheet myWorksheet = myWorkbook.Worksheets["Sheet1"];
                        int recordIndex = 4;
                        foreach (var item in model)
                        {
                            myWorksheet.Cells[recordIndex, 1].Value = item.STT.ToString();
                            myWorksheet.Cells[recordIndex, 2].Value = item.CB_PT_BIENSO;
                            myWorksheet.Cells[recordIndex, 3].Value = item.CB_PT_CQCAPGPXTL == null ? "" : item.CB_PT_CQCAPGPXTL.ToString();
                            myWorksheet.Cells[recordIndex, 4].Value = item.CB_PT_SOGPXTL == null ? "" : item.CB_PT_SOGPXTL.ToString();
                            myWorksheet.Cells[recordIndex, 5].Value = item.CB_PT_NGAYGPXTL == null ? "" : item.CB_PT_NGAYGPXTL.ToString();
                            myWorksheet.Cells[recordIndex, 6].Value = item.CB_PT_NGAYHHGPXTL == null ? "" : item.CB_PT_NGAYHHGPXTL.ToString();
                            recordIndex++;
                        }
                        string tendvgtvt = SearchModel.pDVGTVT_MA == null ? null : _db.GetOne<SDONVIGTVT>(x => x.DVGTVT_MA == SearchModel.pDVGTVT_MA).DVGTVT_TEN;
                        myWorksheet.Cells[2, 1].Value = "Đơn vị kinh doanh vận tải: " + tendvgtvt;
                        excelPackage.Save();
                    }
                    string contentType = string.Empty;
                    string CurrentFileName = Server.MapPath(@"\Templates\GPS_Excel\CB_DonViHetHanGiayPhepNEW.xlsx");
                    if (CurrentFileName.Contains(".xlsx"))
                    {
                        contentType = "application/msexcel";
                    }
                    return File(CurrentFileName, contentType, string.Concat("CB_PhuongTinHetHanGiayPhep_" + DateTime.Now.ToShortDateString() + ".xlsx"));
                }
                catch (Exception ex)
                {
                    TempData["Message"] = ex.ToString();
                    return RedirectToAction("Index");
                }
            }
            else
            {
                ViewBag.TotalRow = entities.Count();
                var pageIndex = SearchModel.Page ?? 1;
                SearchModel.SearchResults = model.ToPagedList(pageIndex, GPS.COMMON.Constants.PageSize);
                return View(SearchModel);
            }
        }
       
        #endregion

        #region funtion
        public GPS.MODELS.ApplicationUser getCurrentUser()
        {
            ApplicationDbContext dbUser = new ApplicationDbContext();
            string userId = User.Identity.GetUserId();
            ApplicationUser _currentUser = dbUser.Users.Find(userId);
            return _currentUser;
        }

        public void initialCategorySearchAction()
        {
            //ViewBag.lstDVGTVT = new SelectList(_db.Filter<SDONVIGTVT>(x => x.DVGTVT_MAQL == "40"), "DVGTVT_MA", "DVGTVT_TEN");
        }

        public List<RepostModelGPS_CANHBAO_GPXTL> Getdata(ViewReportModelGPS_CANHBAO_GPXTL SearchModel)
        {
            var param2 = new OracleParameter("pDVGTVT_MA", OracleDbType.Varchar2, (SearchModel.pDVGTVT_MA == null ? DBNull.Value : (object)SearchModel.pDVGTVT_MA), ParameterDirection.Input);
            var param3 = new OracleParameter("pRET", OracleDbType.RefCursor, ParameterDirection.Output);
            var entities = _db.DbContext.Database.SqlQuery<RepostModelGPS_CANHBAO_GPXTL>("BEGIN GPS_CANHBAO.GPS_CANHBAO_PT(:pDVGTVT_MA,:pRET); end;", param2, param3).ToList();
            return entities;
        }

        #endregion
    }
}